package com.taotao.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.result.EUTreeNodeResult;
import com.taotao.common.result.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCatService;
@Service
public class ContentCatServiceImpl implements ContentCatService {
	@Autowired
	private TbContentCategoryMapper contentCatMapper;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<EUTreeNodeResult> getContentCatList(Long parentId) {
		TbContentCategoryExample example=new TbContentCategoryExample();
		Criteria criteria= example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbContentCategory> list= contentCatMapper.selectByExample(example);
		
		List<EUTreeNodeResult> nodeList=new ArrayList();
		for(TbContentCategory contentCat:list){
			EUTreeNodeResult node=new EUTreeNodeResult();
			node.setId(contentCat.getId());
			node.setText(contentCat.getName());
			node.setState(contentCat.getIsParent()?"closed":"open");
			nodeList.add(node);
		}
		return nodeList;
	}
	
	public TaotaoResult addNode(Long parentId,String name)throws Exception{
		Date date=new Date();
		TbContentCategory node=new TbContentCategory();
		node.setParentId(parentId);
		node.setName(name);
		node.setCreated(date);
		node.setUpdated(date);
		node.setSortOrder(1);
		node.setStatus(1);
		node.setIsParent(false);
		contentCatMapper.insert(node);
		TbContentCategory parentNode=contentCatMapper.selectByPrimaryKey(parentId);
		if(!parentNode.getIsParent()){
			parentNode.setIsParent(true);
			contentCatMapper.updateByPrimaryKey(parentNode);
		}
		return TaotaoResult.ok(node);
	}
}
